package com.eshipenet.shipnet.edgeboxrpc.util;

import com.eshipenet.shipnet.edgeboxrpc.grpc.EdgeBoxRepoGrpcImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import scala.collection.Seq;
import scala.util.Try;
import squirrel.JSONQuery;
import squirrel.ParameterizedSQL;
import squirrel.SqlSelectAst;
import squirrel.SqlValue;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class FormatSql {

    public static Log log = LogFactory.getLog(FormatSql.class);


    public static Map<String,Object> getFormatSql(JSONQuery jsonQuery) {

        String sql = "";
        Map<String,Object> map = new HashMap<>();
        Try<SqlSelectAst> ast = jsonQuery.toSqlAst();

        boolean isSuccess = ast.isSuccess();

        try{

            if (!isSuccess) {
                log.error("ast--isSuccess:" + ast.failed());
                throw new Exception("ast.failed():"+ast.failed());
            } else {

                Try<ParameterizedSQL> toSql = ast.get().toSQL();
                isSuccess = toSql.isSuccess();

                if (!isSuccess) {
                    log.error("toSql--isSuccess:" + toSql.failed());
                    throw new Exception("toSql.failed():"+toSql.failed());
                } else {

                    sql = toSql.get().sql();
                    map.put("sql",sql);
                    map.put("args",toSql.get().args());

                }

            }

            return map;

        }catch (Exception e){
           e.printStackTrace();
        }

        return map;
    }



    public static Object[] sqlValueToObject(Seq<SqlValue> value) {

        scala.collection.Iterator<SqlValue> iterator = value.seq().iterator();

        java.util.List<Object> it_list = new ArrayList<Object>();

        while (iterator.hasNext()) {
            it_list.add(iterator.next().toValue());
        }

        Object[] objAry = it_list.toArray();

        return objAry;

    }



}

